{
 "cells": [
  {
   "metadata": {
    "collapsed": true
   },
   "cell_type": "markdown",
   "source": [
    "#### 如何实现记忆功能\n",
    "实际上，模型本身是不会记忆任何上下文的，只能依靠用户本身的输入去产生输出\n",
    "实现这个记忆功能，就需要额外的模块去保存我们和模型对话的上下文信息，然后在下一次请求时，把所有历史信息都输入给模型，让模型输出最终结果\n",
    "而在LangChain中，提供这个功能的模块就称为Memory(记忆)，用于存储用户和模型交互的历史信息"
   ],
   "id": "f0e6886a9eccdf57"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "#### 什么是Memory\n",
    "    Memory，是LangChain中用于多轮对话中保存和管理上下文信息(比如文本、图像、音频等)的组件\n",
    "    它让应用能够记住用户之前说了什么，从而实现对话的上下文感知能力，为构建真正只能和上下文感知的链式对话系统提供了基础"
   ],
   "id": "db70ca3bc51f110d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-26T05:44:05.340328Z",
     "start_time": "2025-09-26T05:44:05.334217Z"
    }
   },
   "cell_type": "markdown",
   "source": "#### 不使用Memory实现记忆功能",
   "id": "db693f74569006cd"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-10T05:53:08.172347Z",
     "start_time": "2025-10-10T05:53:06.189927Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "import os\n",
    "\n",
    "os.environ['OPENAI_BASE_URL'] = 'https://vip.apiyi.com/v1'\n",
    "os.environ['OPENAI_API_KEY'] = 'sk-xU64G4hXJ4L47ko3764958119dB245D2BdEcE528767dA1Da'\n",
    "\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")"
   ],
   "id": "768a20896b5b54e4",
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain_core.messages import AIMessage, HumanMessage\n",
    "\n",
    "\n",
    "def chat_with_model(question):\n",
    "    #提供提示词模板\n",
    "    prompt_template = ChatPromptTemplate.from_messages([(\"system\", \"你是一个人工智能助手\"), (\"human\", f\"{question}\")])\n",
    "\n",
    "    while True:\n",
    "        chain = prompt_template | chat_model\n",
    "        response = chain.invoke({\"question\": question})\n",
    "        print(f\"模型回复:{response.content}\")\n",
    "        #继续获取用户的问题\n",
    "        user_input = input(\"你还有其他的问题吗?(输入'退出'时，结束会话)\")\n",
    "        if user_input == \"退出\":\n",
    "            break\n",
    "        prompt_template.messages.append(AIMessage(content=response.content))\n",
    "        prompt_template.messages.append(HumanMessage(content=user_input))\n",
    "\n",
    "chat_with_model(\"你是谁?\")"
   ],
   "id": "a613e62ddd918546",
   "outputs": [],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
